<?php
if (!defined('_PS_VERSION_'))
	exit;
require_once('pecmslider_class.php');
class peCmSlider extends Module {
	public function __construct() {
		$this->name = 'pecmslider';
		$this->tab = 'front_office_features';
		$this->version = 1.0;
		$this->author = 'PrestaExt.com';
		$this->need_instance = 0;

		parent::__construct();

		$this->displayName = $this->l('PE Cms Slider');
		$this->description = $this->l('PE Cms Slider');
	}
	
	public function install() {
		if (parent::install() == false || 
			$this->registerHook('top') == false || 
			$this->registerHook('header') == false )
				return false;
				
		return true;
	}

	public function getContent() {
		$output = '<h2>'.$this->displayName.'</h2>';
		if (Tools::isSubmit('submitpecmslider')) {
			$category = Tools::getValue('category');
			$category = implode(',', $category);
			$peNumber = Tools::getValue('penumber');
			$peStyle = Tools::getValue('pestyle') ? Tools::getValue('pestyle') : 1;
			$peWidth = Tools::getValue('pewidth') ? Tools::getValue('pewidth') : 980;
			$peHeight = Tools::getValue('peheight') ? Tools::getValue('peheight') : 340;
			$peWordlimit = Tools::getValue('pewordlimit') ? Tools::getValue('pewordlimit') : 20;
			$peLinkTitle = Tools::getValue('pelinktitle');
			$peonlyhome = Tools::getValue('peonlyhome');
			
			//validate
			if (!$peNumber)
				$output .= '<div class="alert error">'.$this->l('Please fill in the "cms displayed" field.').'</div>';
			elseif ((int)($peNumber) == 0)
				$output .= '<div class="alert error">'.$this->l('Invalid number.').'</div>';
			else {
				Configuration::updateValue('PE_CMSLIDER_CATEGORY', $category);
				Configuration::updateValue('PE_CMSLIDER_NUMBER', $peNumber);
				Configuration::updateValue('PE_CMSLIDER_STYLE', $peStyle);
				Configuration::updateValue('PE_CMSLIDER_WIDTH', $peWidth);
				Configuration::updateValue('PE_CMSLIDER_HEIGHT', $peHeight);
				Configuration::updateValue('PE_CMSLIDER_WORDLIMIT', $peWordlimit);
				Configuration::updateValue('PE_CMSLIDER_LINKTITLE', $peLinkTitle);			
				Configuration::updateValue('PE_CMSLIDER_ONLYHOME', $peonlyhome);			
				
				$output .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('Confirmation').'" />'.$this->l('Settings updated').'</div>';
			}
		}
		
		if (Tools::isSubmit('submitpecmslider_image')) {
			//image thumb size
			$pe_wthumb1 = Tools::getValue('pe_wthumb1') ? Tools::getValue('pe_wthumb1') : 70;
			$pe_hthumb1 = Tools::getValue('pe_hthumb1') ? Tools::getValue('pe_hthumb1') : 25;
			$pe_wthumb2 = Tools::getValue('pe_wthumb2') ? Tools::getValue('pe_wthumb2') : 140;
			$pe_hthumb2 = Tools::getValue('pe_hthumb2') ? Tools::getValue('pe_hthumb2') : 70;
			
			Configuration::updateValue('PE_CMSLIDER_THUMBWIDTH1', $pe_wthumb1);
			Configuration::updateValue('PE_CMSLIDER_THUMBHEIGHT1', $pe_hthumb1);
			Configuration::updateValue('PE_CMSLIDER_THUMBWIDTH2', $pe_wthumb2);
			Configuration::updateValue('PE_CMSLIDER_THUMBHEIGHT2', $pe_hthumb2);
			
			$output .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('Confirmation').'" />'.$this->l('Settings updated').'</div>';
		}
		
		return $output.$this->peSettingForm().$this->peSetImageThumb();
	}

	public function peSettingForm() {	
		$category = peProductHtml::getCategories();
		$listCat = array();
		$selected = explode(',', Configuration::get('PE_CMSLIDER_CATEGORY')); 

		foreach ($category as $value) {			
			$listCat[] = array('value' => $value['id_cms_category'], 'text' => $value['name']);
		}
		$listCatSelect = peProductHtml::genericlist($listCat, 'category[]', 'class="category" multiple="true"', 'value', 'text', $selected);
				
		$selected = Configuration::get('PE_CMSLIDER_STYLE');
		$styleSelect[] = array('value'=> 1, 'text' => 'Style 1');
		$styleSelect[] = array('value'=> 2, 'text' => 'Style 2');
		$styleSelect[] = array('value'=> 3, 'text' => 'Style 3');
		$styleSelect[] = array('value'=> 4, 'text' => 'Style 4');
		$styleSelects = peProductHtml::genericlist($styleSelect, 'pestyle', 'class="pestyle"', 'value', 'text', $selected);
		
		$output = '
		<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
			<fieldset><legend><img src="'.$this->_path.'logo.gif" alt="" title="" />'.$this->l('Settings').'</legend>
				<label>'.$this->l('Cms Category').'</label>
				<div class="margin-form">'.$listCatSelect.'</div>
				
				<label>'.$this->l('cms displayed').'</label>
				<div class="margin-form">
					<input type="text" name="penumber" value="'.(int)(Configuration::get('PE_CMSLIDER_NUMBER')).'" />
					<p class="clear">'.$this->l('Set the number of cms to be displayed in this slider module').'</p>
				</div>
				
				<label>'.$this->l('Width').'</label>
				<div class="margin-form">
					<input type="text" name="pewidth" value="'.(int)(Configuration::get('PE_CMSLIDER_WIDTH')).'" />
					<p class="clear">'.$this->l('Set width of slider module (examples: 980)').'</p>
				</div>
				
				<label>'.$this->l('Height').'</label>
				<div class="margin-form">
					<input type="text" name="peheight" value="'.(int)(Configuration::get('PE_CMSLIDER_HEIGHT')).'" />
					<p class="clear">'.$this->l('Set height of slider module (examples: 340)').'</p>
				</div>
				
				<label>'.$this->l('Word limit').'</label>
				<div class="margin-form">
					<input type="text" name="pewordlimit" value="'.(int)(Configuration::get('PE_CMSLIDER_WORDLIMIT')).'" />
					<p class="clear">'.$this->l('Set description word limit (examples: 20)').'</p>
				</div>
				
				<label>'.$this->l('Linked Titles').'</label>
				<div class="margin-form">
					<input type="radio" name="pelinktitle" id="display_on" value="1" '.(Tools::getValue('pelinktitle', Configuration::get('PE_CMSLIDER_LINKTITLE')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="display_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="pelinktitle" id="display_off" value="0" '.(!Tools::getValue('pelinktitle', Configuration::get('PE_CMSLIDER_LINKTITLE')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="display_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
				</div>
				
				<label>'.$this->l('Only homepage').'</label>
				<div class="margin-form">
					<input type="radio" name="peonlyhome" id="display_on" value="1" '.(Tools::getValue('peonlyhome', Configuration::get('PE_CMSLIDER_ONLYHOME')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="display_on"> <img src="../img/admin/enabled.gif" alt="'.$this->l('Enabled').'" title="'.$this->l('Enabled').'" /></label>
					<input type="radio" name="peonlyhome" id="display_off" value="0" '.(!Tools::getValue('peonlyhome', Configuration::get('PE_CMSLIDER_ONLYHOME')) ? 'checked="checked" ' : '').'/>
					<label class="t" for="display_off"> <img src="../img/admin/disabled.gif" alt="'.$this->l('Disabled').'" title="'.$this->l('Disabled').'" /></label>
				</div>
				
				<label>'.$this->l('Style').'</label>
					<div class="margin-form">'.$styleSelects.'
					<p class="clear">'.$this->l('Set style for slider module').'</p>
				</div>
				
				<center><input type="submit" name="submitpecmslider" value="'.$this->l('Save').'" class="button" /></center>
			</fieldset>
		</form>';
		
		return $output;
	}
	
	public function peSetImageThumb() {
		$output = '
		<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
			<fieldset><legend><img src="'.$this->_path.'logo.gif" alt="" title="" />'.$this->l('Set Image Thumbnail').'</legend>
				<label>'.$this->l('Thumb Width').'</label>
				<div class="margin-form">
					<input type="text" name="pe_wthumb1" value="'.(int)(Configuration::get('PE_CMSLIDER_THUMBWIDTH1')).'" />
					<p class="clear">'.$this->l('Set thumbnail width for style 1 (examples: 70)').'</p>
				</div>
				
				<label>'.$this->l('Thumb Height').'</label>
				<div class="margin-form">
					<input type="text" name="pe_hthumb1" value="'.(int)(Configuration::get('PE_CMSLIDER_THUMBHEIGHT1')).'" />
					<p class="clear">'.$this->l('Set thumbnail height for style 1 (examples: 25)').'</p>
				</div>
				
				<label>'.$this->l('Thumb Width').'</label>
				<div class="margin-form">
					<input type="text" name="pe_wthumb2" value="'.(int)(Configuration::get('PE_CMSLIDER_THUMBWIDTH2')).'" />
					<p class="clear">'.$this->l('Set thumbnail width of another slider (examples: 140)').'</p>
				</div>
				
				<label>'.$this->l('Thumb Height').'</label>
				<div class="margin-form">
					<input type="text" name="pe_hthumb2" value="'.(int)(Configuration::get('PE_CMSLIDER_THUMBHEIGHT2')).'" />
					<p class="clear">'.$this->l('Set thumbnail hegiht of another slider (examples: 70)').'</p>
				</div>
				
				<center><input type="submit" name="submitpecmslider_image" value="'.$this->l('Save').'" class="button" /></center>
			</fieldset>
		</form>';
		
		return $output;
	}
	
	public function hookTop ($params) {
		global $smarty;
		$baseUrl = $smarty->tpl_vars;
		$baseUrl = $baseUrl['base_dir']->value;

		$peStyle = Configuration::get('PE_CMSLIDER_STYLE');
		$peWidth = Configuration::get('PE_CMSLIDER_WIDTH');
		$peHeight = Configuration::get('PE_CMSLIDER_HEIGHT');
		$peLinkTitle = Configuration::get('PE_CMSLIDER_LINKTITLE');
		$peonlyhome = Configuration::get('PE_CMSLIDER_ONLYHOME');
		$peCms = peCmSlider::getCmsData($params['cookie']->id_lang);
		if (($peonlyhome && peCmSlider::curPageURL() != $baseUrl) || !$peCms) {
			return;
		}

		$smarty->assign('pecms', $peCms);
		$smarty->assign('pestyle', $peStyle);
		$smarty->assign('pewidth', $peWidth);
		$smarty->assign('peheight', $peHeight);
		$smarty->assign('pelinktitle', $peLinkTitle);

		return $this->display(__FILE__, 'pecmslider.tpl');
	}
		
	public function hookHeader($params) {		
		Tools::addJS(($this->_path).'js/jquery.easing.js');
		Tools::addJS(($this->_path).'js/script.js');
		$peStyle = Configuration::get('PE_CMSLIDER_STYLE', $peStyle);

		if ($peStyle == 1) {
			Tools::addCSS(($this->_path).'css/style1.css', 'all');
			Tools::addJS(($this->_path).'js/style1.js');
		}
		if ($peStyle == 2) {
			Tools::addCSS(($this->_path).'css/style2.css', 'all');
			Tools::addJS(($this->_path).'js/style2.js');
		}		
		if ($peStyle == 3) {
			Tools::addCSS(($this->_path).'css/style3.css', 'all');
			Tools::addJS(($this->_path).'js/style3.js');
		}		
		if ($peStyle == 4) {
			Tools::addCSS(($this->_path).'css/style4.css', 'all');
			Tools::addJS(($this->_path).'js/style4.js');
		}		
	}
		
	public function getCmsData($id_lang) {
		global $smarty;
		$baseUrl = $smarty->tpl_vars;
		$baseUrl = $baseUrl['base_dir']->value;
		
		$peWidth = Configuration::get('PE_CMSLIDER_WIDTH');
		$peHeight = Configuration::get('PE_CMSLIDER_HEIGHT');
		//get Thumb size
		$pe_wthumb1 = Configuration::get('PE_CMSLIDER_THUMBWIDTH1');
		$pe_hthumb1 = Configuration::get('PE_CMSLIDER_THUMBHEIGHT1');
		$pe_wthumb2 = Configuration::get('PE_CMSLIDER_THUMBWIDTH2');
		$pe_hthumb2 = Configuration::get('PE_CMSLIDER_THUMBHEIGHT2');
	
		$category = Configuration::get('PE_CMSLIDER_CATEGORY'); 
		$peNumber = Configuration::get('PE_CMSLIDER_NUMBER') ? Configuration::get('PE_CMSLIDER_NUMBER') : 5; 
		$peWordlimit = (Configuration::get('PE_CMSLIDER_WORDLIMIT', $peWordlimit)) ? Configuration::get('PE_CMSLIDER_WORDLIMIT', $peWordlimit) : 20;
		$query = '
		SELECT DISTINCT c.id_cms, c.*, cl.*  
		FROM `'._DB_PREFIX_.'cms` c 
		LEFT JOIN `'._DB_PREFIX_.'cms_lang` cl ON (c.`id_cms` = cl.`id_cms`) 
		LEFT JOIN `'._DB_PREFIX_.'cms_category` ca ON (c.`id_cms_category` = ca.`id_cms_category`)  
		WHERE c.`active` = 1 
		AND c.`id_cms_category` IN ('.$category.') 
		AND cl.`id_lang` = '.(int)($id_lang) .' 
		LIMIT 0, '.$peNumber.'';
		
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($query);
		
		foreach ($result as &$item) {			
			$link = new Link();			
			$item['link'] = $link->getCMSLink((int)($item['id_cms']), $item['link_rewrite']);
			$item['desc'] = peProductHtml::wordLimit(strip_tags($item['content']), $peWordlimit);
			
			//get Image
			preg_match_all('/src="([^"]+)"/i', $item['content'], $matches);// load the first image from introtex or fulltext
			if (empty($matches[1][0])) {
				$item['linkimage'] = '';
				$item['linkimagethumb'] = '';
			}else {
				$item['linkimage'] = $baseUrl.'modules/pecmslider/timthumb.php?src='.$matches[1][0].'&w='.$peWidth.'&h='.$peHeight;
				$item['linkimagethumb'] =  $baseUrl.'modules/pecmslider/timthumb.php?src='.$matches[1][0].'&w='.$pe_wthumb1.'&h='.$pe_hthumb1;
				$item['linkimagethumb1'] =  $baseUrl.'modules/pecmslider/timthumb.php?src='.$matches[1][0].'&w='.$pe_wthumb2.'&h='.$pe_hthumb2;
			}
		}

		return $result;
	}
	
	function curPageURL() {
		$pageURL = 'http';
		if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
		$pageURL .= "://";

		if ($_SERVER["SERVER_PORT"] != "80") {
			$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
		} 
		else {
			$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
		}

		return $pageURL;
	}

}